<?php
session_start();
header('Content-Type: application/json');

// 检查登录状态
if (!isset($_SESSION['admin_logged_in']) || !$_SESSION['admin_logged_in']) {
    echo json_encode(['success' => false, 'message' => '未登录']);
    exit;
}

require_once __DIR__ . '/../core/config.php';
try {
    $db = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=' . DB_CHARSET, DB_USER, DB_PASS);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo json_encode(['success' => false, 'message' => '数据库连接失败']);
    exit;
}

// 记录操作日志
function logAction($action, $details) {
    global $db;
    $stmt = $db->prepare("INSERT INTO action_logs (user, action, details, ip_address) VALUES (?, ?, ?, ?)");
    $stmt->execute(['admin', $action, $details, $_SERVER['REMOTE_ADDR'] ?? '']);
}

// 获取请求动作
$action = $_POST['action'] ?? $_GET['action'] ?? '';

switch ($action) {
    case 'toggle_plugin':
        $id = $_POST['id'] ?? 0;
        $status = $_POST['status'] ?? '';
        
        if ($id && in_array($status, ['active', 'inactive'])) {
            $stmt = $db->prepare("UPDATE plugins SET status = ? WHERE id = ?");
            if ($stmt->execute([$status, $id])) {
                logAction('update', "切换插件状态: ID=$id, 状态=$status");
                echo json_encode(['success' => true]);
            } else {
                echo json_encode(['success' => false, 'message' => '更新失败']);
            }
        } else {
            echo json_encode(['success' => false, 'message' => '参数错误']);
        }
        break;

    case 'delete_plugin':
        $id = $_POST['id'] ?? 0;
        
        if ($id) {
            // 获取插件信息
            $stmt = $db->prepare("SELECT folder FROM plugins WHERE id = ?");
            $stmt->execute([$id]);
            $plugin = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($plugin) {
                // 删除数据库记录
                $stmt = $db->prepare("DELETE FROM plugins WHERE id = ?");
                if ($stmt->execute([$id])) {
                    // 删除分类关联
                    $stmt = $db->prepare("DELETE FROM plugin_categories WHERE plugin_id = ?");
                    $stmt->execute([$id]);
                    
                    logAction('delete', "删除插件: " . $plugin['folder']);
                    echo json_encode(['success' => true]);
                } else {
                    echo json_encode(['success' => false, 'message' => '删除失败']);
                }
            } else {
                echo json_encode(['success' => false, 'message' => '插件不存在']);
            }
        } else {
            echo json_encode(['success' => false, 'message' => '参数错误']);
        }
        break;

    case 'add_category':
        $name = $_POST['name'] ?? '';
        $description = $_POST['description'] ?? '';
        $sort_order = (int)($_POST['sort_order'] ?? 0);
        
        if ($name) {
            $stmt = $db->prepare("INSERT INTO categories (name, description, sort_order) VALUES (?, ?, ?)");
            if ($stmt->execute([$name, $description, $sort_order])) {
                logAction('create', "添加分类: $name");
                echo json_encode(['success' => true]);
            } else {
                echo json_encode(['success' => false, 'message' => '添加失败']);
            }
        } else {
            echo json_encode(['success' => false, 'message' => '分类名称不能为空']);
        }
        break;

    case 'edit_category':
        $id = $_POST['id'] ?? 0;
        $name = $_POST['name'] ?? '';
        $description = $_POST['description'] ?? '';
        $sort_order = (int)($_POST['sort_order'] ?? 0);
        
        if ($id && $name) {
            $stmt = $db->prepare("UPDATE categories SET name = ?, description = ?, sort_order = ? WHERE id = ?");
            if ($stmt->execute([$name, $description, $sort_order, $id])) {
                logAction('update', "编辑分类: $name");
                echo json_encode(['success' => true]);
            } else {
                echo json_encode(['success' => false, 'message' => '更新失败']);
            }
        } else {
            echo json_encode(['success' => false, 'message' => '参数错误']);
        }
        break;

    case 'delete_category':
        $id = $_POST['id'] ?? 0;
        
        if ($id) {
            // 获取分类信息
            $stmt = $db->prepare("SELECT name FROM categories WHERE id = ?");
            $stmt->execute([$id]);
            $category = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($category) {
                // 删除分类关联
                $stmt = $db->prepare("DELETE FROM plugin_categories WHERE category_id = ?");
                $stmt->execute([$id]);
                
                // 删除分类
                $stmt = $db->prepare("DELETE FROM categories WHERE id = ?");
                if ($stmt->execute([$id])) {
                    logAction('delete', "删除分类: " . $category['name']);
                    echo json_encode(['success' => true]);
                } else {
                    echo json_encode(['success' => false, 'message' => '删除失败']);
                }
            } else {
                echo json_encode(['success' => false, 'message' => '分类不存在']);
            }
        } else {
            echo json_encode(['success' => false, 'message' => '参数错误']);
        }
        break;

    case 'get_category':
        $id = $_GET['id'] ?? 0;
        
        if ($id) {
            $stmt = $db->prepare("SELECT * FROM categories WHERE id = ?");
            $stmt->execute([$id]);
            $category = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($category) {
                echo json_encode(['success' => true, 'category' => $category]);
            } else {
                echo json_encode(['success' => false, 'message' => '分类不存在']);
            }
        } else {
            echo json_encode(['success' => false, 'message' => '参数错误']);
        }
        break;

    case 'set_plugin_category':
        $plugin_id = $_POST['plugin_id'] ?? 0;
        $category_id = $_POST['category_id'] ?? '';
        
        if ($plugin_id) {
            // 删除现有关联
            $stmt = $db->prepare("DELETE FROM plugin_categories WHERE plugin_id = ?");
            $stmt->execute([$plugin_id]);
            
            // 添加新关联
            if ($category_id) {
                $stmt = $db->prepare("INSERT INTO plugin_categories (plugin_id, category_id) VALUES (?, ?)");
                $stmt->execute([$plugin_id, $category_id]);
            }
            
            logAction('update', "设置插件分类: 插件ID=$plugin_id, 分类ID=$category_id");
            echo json_encode(['success' => true]);
        } else {
            echo json_encode(['success' => false, 'message' => '参数错误']);
        }
        break;

    case 'sync_plugins':
        // 扫描插件目录
        $pluginsDir = __DIR__ . '/../plugins/';
        $plugins = [];
        
        if (is_dir($pluginsDir)) {
            $folders = scandir($pluginsDir);
            foreach ($folders as $folder) {
                if ($folder !== '.' && $folder !== '..' && is_dir($pluginsDir . $folder)) {
                    $pluginJson = $pluginsDir . $folder . '/plugin.json';
                    if (file_exists($pluginJson)) {
                        $pluginData = json_decode(file_get_contents($pluginJson), true);
                        if ($pluginData) {
                            $plugins[] = [
                                'folder' => $folder,
                                'name' => $pluginData['name'] ?? $folder,
                                'description' => $pluginData['description'] ?? '',
                                'version' => $pluginData['version'] ?? '1.0.0',
                                'author' => $pluginData['author'] ?? '',
                                'tags' => $pluginData['tags'] ?? []
                            ];
                        }
                    }
                }
            }
        }
        
        // 同步到数据库
        foreach ($plugins as $plugin) {
            $stmt = $db->prepare("SELECT id FROM plugins WHERE folder = ?");
            $stmt->execute([$plugin['folder']]);
            $existing = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($existing) {
                // 更新现有插件
                $stmt = $db->prepare("UPDATE plugins SET name = ?, description = ?, version = ?, author = ?, tags = ? WHERE folder = ?");
                $stmt->execute([
                    $plugin['name'],
                    $plugin['description'],
                    $plugin['version'],
                    $plugin['author'],
                    json_encode($plugin['tags']),
                    $plugin['folder']
                ]);
            } else {
                // 添加新插件
                $stmt = $db->prepare("INSERT INTO plugins (folder, name, description, version, author, tags, status) VALUES (?, ?, ?, ?, ?, ?, 'inactive')");
                $stmt->execute([
                    $plugin['folder'],
                    $plugin['name'],
                    $plugin['description'],
                    $plugin['version'],
                    $plugin['author'],
                    json_encode($plugin['tags'])
                ]);
            }
        }
        
        logAction('sync', "同步插件: 发现 " . count($plugins) . " 个插件");
        echo json_encode(['success' => true, 'message' => '同步完成，发现 ' . count($plugins) . ' 个插件']);
        break;

    case 'upload_plugin':
        if (isset($_FILES['plugin_file']) && $_FILES['plugin_file']['error'] === UPLOAD_ERR_OK) {
            $file = $_FILES['plugin_file'];
            $fileName = $file['name'];
            $fileTmpPath = $file['tmp_name'];
            
            // 检查文件类型
            if (pathinfo($fileName, PATHINFO_EXTENSION) !== 'zip') {
                echo json_encode(['success' => false, 'message' => '只支持ZIP格式文件']);
                break;
            }
            
            // 创建临时目录
            $tempDir = __DIR__ . '/../temp/' . uniqid();
            if (!is_dir($tempDir)) {
                mkdir($tempDir, 0755, true);
            }
            
            // 解压文件
            $zip = new ZipArchive;
            if ($zip->open($fileTmpPath) === TRUE) {
                $zip->extractTo($tempDir);
                $zip->close();
                
                // 检查插件结构
                $pluginJson = $tempDir . '/plugin.json';
                if (!file_exists($pluginJson)) {
                    echo json_encode(['success' => false, 'message' => '插件文件缺少plugin.json']);
                    break;
                }
                
                $pluginData = json_decode(file_get_contents($pluginJson), true);
                if (!$pluginData || !isset($pluginData['name'])) {
                    echo json_encode(['success' => false, 'message' => 'plugin.json格式错误']);
                    break;
                }
                
                // 生成插件文件夹名
                $folderName = preg_replace('/[^a-zA-Z0-9_-]/', '', strtolower($pluginData['name']));
                $targetDir = __DIR__ . '/../plugins/' . $folderName;
                
                // 检查是否已存在
                if (is_dir($targetDir)) {
                    echo json_encode(['success' => false, 'message' => '插件已存在']);
                    break;
                }
                
                // 移动到插件目录
                if (rename($tempDir, $targetDir)) {
                    // 添加到数据库
                    $stmt = $db->prepare("INSERT INTO plugins (folder, name, description, version, author, tags, status) VALUES (?, ?, ?, ?, ?, ?, 'inactive')");
                    $stmt->execute([
                        $folderName,
                        $pluginData['name'],
                        $pluginData['description'] ?? '',
                        $pluginData['version'] ?? '1.0.0',
                        $pluginData['author'] ?? '',
                        json_encode($pluginData['tags'] ?? [])
                    ]);
                    
                    logAction('create', "上传插件: " . $pluginData['name']);
                    echo json_encode(['success' => true, 'message' => '插件上传成功']);
                } else {
                    echo json_encode(['success' => false, 'message' => '文件移动失败']);
                }
            } else {
                echo json_encode(['success' => false, 'message' => 'ZIP文件解压失败']);
            }
        } else {
            echo json_encode(['success' => false, 'message' => '文件上传失败']);
        }
        break;

    default:
        echo json_encode(['success' => false, 'message' => '未知操作']);
        break;
} 